﻿using Newtonsoft.Json;
using PioneerBoilerplate.Model.Admin;
using PioneerBoilerplate.Repository.Base;
using PioneerBoilerplate.Util;
using PioneerBoilerplate.Util.Helpers;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace PioneerBoilerplate.Repository.Seed
{
    public class DataSeeding:Data
    {
        public DataSeeding()
        {
            var filePath = Path.Combine(AppContext.BaseDirectory, "Db/Data/data.json").ToPath();
            var jsonData = FileHelper.ReadFile(filePath);
            var data = JsonConvert.DeserializeObject<Data>(jsonData);

            this.ApiTree = data.ApiTree;
            this.ViewTree = data.ViewTree;
            this.PermissionTree = data.PermissionTree;

            this.Views = data.ViewTree;
            this.Permissions = PermissionTreeToArray(data.PermissionTree);

            this.Views = ViewTreeToArray(data.ViewTree);
            this.DictionaryTypes = data.DictionaryTypes;
            this.Dictionaries = data.Dictionaries;
            this.Apis = data.Apis;
            this.Users = data.Users;
            this.Roles = data.Roles;
            this.UserRoles = data.UserRoles;
            this.RolePermissions = data.RolePermissions;
            this.PermissionApis = data.PermissionApis;
        }

        private static PermissionEntity[] PermissionTreeToArray(PermissionEntity[] tree) 
        {

            List<PermissionEntity> permissions = tree.ToList();


            for (int i = 0; i < tree.Length; i++)
            {
                if (tree[i]?.Childs != null && tree[i]?.Childs.Count > 0)
                {
                    permissions.AddRange(tree[i].Childs);
                }

                tree[i].Childs = null;
                if (!tree.Where(x => x.Id == tree[i].Id).Any())
                    permissions.Add(tree[i]);

                tree = permissions.ToArray();
            }

            return permissions.ToArray();
        }

        private static ViewEntity[] ViewTreeToArray(ViewEntity[] tree)
        {

            List<ViewEntity> views = tree.ToList();


            for (int i = 0; i < tree.Length; i++)
            {
                if (tree[i]?.Childs != null && tree[i]?.Childs.Count > 0)
                {
                    views.AddRange(tree[i].Childs);
                }

                tree[i].Childs = null;
                if (!tree.Where(x => x.Id == tree[i].Id).Any())
                    views.Add(tree[i]);

                tree = views.ToArray();
            }

            return views.ToArray();
        }
    }
}
